package com.leonardo.lengthexample;

import com.leonardo.beanme.InputFieldChangeHandler;
import com.leonardo.beanme.fields.InputField;

public class LengthHandler implements InputFieldChangeHandler {

	private int maxLength;
	private Object lastValue;
	private InputWithLength field;
	
	public LengthHandler(InputWithLength field, int maxLength) {
		if(maxLength < 0)
			throw new IllegalArgumentException("maxlength cannot be negative ");
		
		this.maxLength = maxLength;
		this.lastValue = field.getValue();
		this.field = field;
		
		if(!validLength())
			field.setValue(field.getValue().toString().substring(0, maxLength));
	}
	
	public InputField getField() {
		return field;
	}

	public void onChange() {
		if(!validLength())
			field.setValue(lastValue);
		this.lastValue = field.getValue(); 
	}

	public boolean validLength() {
		return field.getLength() <= maxLength;
	}
	
}
